﻿using JuCheap.Core.IService;
using JuCheap.Core.IService.AppService;
using JuCheap.Core.Model;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.Threading;
using System.Threading.Tasks;

namespace JuCheap.Core.WebApi
{
    /// <summary>
    /// 定时重置demo用户的密码
    /// </summary>
    internal class ChangePasswordTaskService : BackgroundService
    {
        private readonly IServiceScopeFactory _serviceScopeFactory;

        public ChangePasswordTaskService(IServiceScopeFactory serviceScopeFactory)
        {
            _serviceScopeFactory = serviceScopeFactory;
        }

        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            while (!stoppingToken.IsCancellationRequested)
            {
                using (var scope = _serviceScopeFactory.CreateScope())
                {
                    var userService = scope.ServiceProvider.GetService<IUserService>();
                    var sysUserService = scope.ServiceProvider.GetService<ISysUserService>();

                    var userInfo = await sysUserService.FindAsync("2019040221272914193846649638912");
                    var userReq = new UserEditRequestDto
                    {
                        Id = userInfo.Id,
                        LoginName = userInfo.LoginName,
                        Password = "qwaszx",
                        Name = userInfo.Name,
                        DepartmentId = userInfo.DepartmentId
                    };
                    await userService.UpdateAsync(userReq);
                }
                var random = new Random(Guid.NewGuid().GetHashCode()).Next(1, 10);
                await Task.Delay(300000 + random, stoppingToken);
            }
        }
    }
}
